import { ref } from 'vue'
import a1 from '@/assets/a1.mp3'
import a2 from '@/assets/a2.mp3'
import a3 from '@/assets/a3.mp3'
import lotter from '@/assets/lotter.mp3'
import lotterystart from '@/assets/lotterystart.mp3'
import lotteryend from '@/assets/lotteryend.mp3'

export function useBackgroundAudio() {
  const current = ref('OPENING')
  const audio = ref<HTMLAudioElement>(new Audio(lotter))
  audio.value.loop = true

  const isPaused = ref(true)

  function toggleAudio() {
    if (current.value !== 'OPENING' && current.value !== 'CLOSING') {
      if (isPaused.value) {
        play()
      } else {
        pause()
      }
    }
  }

  function play() {
    audio.value.play()
    isPaused.value = false
  }

  function pause() {
    audio.value.pause()
    isPaused.value = true
  }

  function switchAudio(
    type: 'OPENING' | 'CLOSING' | 'LOTTERY' | 'LOTTERY_START' | 'LOTTERY_END' = 'OPENING',
  ) {
    audio.value.pause()

    switch (type) {
      case 'OPENING':
        audio.value = new Audio(a3)
        current.value = 'OPENING'
        break
      case 'CLOSING':
        audio.value = new Audio(a2)
        current.value = 'CLOSING'
        break
      case 'LOTTERY':
        audio.value = new Audio(lotter)
        isPaused.value = false
        current.value = 'LOTTERY'
        break
      case 'LOTTERY_START':
        audio.value = new Audio(lotterystart)
        isPaused.value = false
        current.value = 'LOTTERY_START'
        break
      case 'LOTTERY_END':
        audio.value = new Audio(lotteryend)
        isPaused.value = false
        current.value = 'LOTTERY_END'
        break
    }
    audio.value.loop = true
    audio.value.autoplay = true
  }

  return {
    isPaused,
    switchAudio,
    toggleAudio,
    play,
    pause,
  }
}
